#include "klcustomdelegate.h"
#include <QPushButton>
#include <QPainter>
#include <QPixmap>
#include <QDebug>
#include <QStandardItem>
#include <QMouseEvent>
#include <QLabel>;
#include <QLineEdit>
#include <QApplication>
#include <QTreeView>
#include <QMessageBox>
#include <QComboBox>
#include <QICon>
#include <QPalette>
#include <QProxyStyle>


class CustomComboBoxStyle : public QProxyStyle {
public:
    // 显式定义构造函数，接受 QStyle * 参数
    explicit CustomComboBoxStyle(QStyle* style = nullptr) : QProxyStyle(style) {}


    void drawControl(ControlElement element, const QStyleOption* option, QPainter* painter, const QWidget* widget) const override {
        if (element == CE_ComboBoxLabel) {
            const QStyleOptionComboBox* cbOpt = qstyleoption_cast<const QStyleOptionComboBox*>(option);
            if (cbOpt) {
                // 绘制背景色，但保留下拉按钮部分
                QRect rect = cbOpt->rect;

                // 获取下拉按钮的宽度
                int arrowWidth = widget ? widget->style()->pixelMetric(QStyle::PM_SmallIconSize, cbOpt, widget) : QApplication::style()->pixelMetric(QStyle::PM_SmallIconSize, cbOpt, widget);
                int margin = widget ? widget->style()->pixelMetric(QStyle::PM_FocusFrameHMargin, cbOpt, widget) + 1 : QApplication::style()->pixelMetric(QStyle::PM_FocusFrameHMargin, cbOpt, widget) + 1;

                // 调整背景色的绘制区域，保留边框
                int border = 4; // 边框的宽度
                QRect backgroundRect = rect.adjusted(border, border, -(arrowWidth + margin + border), -border);
                painter->fillRect(backgroundRect, Qt::red); // 绘制背景色

                // 调用基类的 drawControl 方法绘制其他部分
                QProxyStyle::drawControl(element, cbOpt, painter, widget);


                // 调整背景色的绘制区域
               // QRect backgroundRect = rect.adjusted(0, 0, -(arrowWidth + margin), 0);
               // painter->fillRect(backgroundRect, Qt::red); // 绘制背景色

                // 调用基类的 drawControl 方法绘制其他部分
               // QProxyStyle::drawControl(element, cbOpt, painter, widget);


                //painter->fillRect(option->rect, Qt::red); // 绘制背景色
                //QProxyStyle::drawControl(element, option, painter, widget);
            }
        }
        else {
            QProxyStyle::drawControl(element, option, painter, widget);
        }
    }
};




KLCustomDelegate::KLCustomDelegate(QObject* parent) : QStyledItemDelegate(parent)
{
    m_pOpenIcon = new QIcon(":/Resource/expanded.png");
    m_pCloseIcon = new QIcon(":/Resource/noexpanded.png");
}

KLCustomDelegate::~KLCustomDelegate()
{

}

void KLCustomDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QStyleOptionViewItem opt = option;
    ButtonState state = getState(index);
    
    if (index.column() == 2) {  // 第3列绘制按钮

        painter->save();
        painter->setRenderHint(QPainter::Antialiasing);

        // 检查索引是否为空或无效
        if (!index.data().isValid() || index.data().toString().isEmpty()) {
            // 绘制默认的背景色
            painter->fillRect(option.rect, Qt::transparent);
        } else {
            // 根据状态绘制不同的底色
            switch (state) {
            case StateNormal:
                painter->fillRect(option.rect, Qt::transparent);
                break;
            case StateSelected:
                painter->fillRect(option.rect, Qt::transparent);
                break;
            case StateDisabled:
                painter->fillRect(option.rect, Qt::transparent);
                break;
            }

            // 绘制边框
            painter->setPen(Qt::white);
            // 绘制上边框
            painter->drawLine(opt.rect.topLeft(), opt.rect.topRight());

            // 绘制下边框
            painter->drawLine(opt.rect.bottomLeft(), opt.rect.bottomRight());

            // 绘制图标
            QPixmap iconPixmap;
            switch (state) {
            case StateNormal:
                iconPixmap = QPixmap(":/Resource/Autorangetime.png");
                break;
            case StateSelected:
                iconPixmap = QPixmap(":/Resource/Ch.png");
                break;
            case StateDisabled:
                iconPixmap = QPixmap(":/Resource/Group.png");
                break;
            }

            if (!iconPixmap.isNull()) {
                painter->drawPixmap(option.rect.center() - QPoint(iconPixmap.width() / 2, iconPixmap.height() / 2), iconPixmap);
            }

        }
        painter->restore();
    } else if(index.column() == 3) {
        painter->save();
        painter->setRenderHint(QPainter::Antialiasing);
        if (!index.data().isValid() || index.data().toString().isEmpty()) {
            // 绘制默认的背景色
            painter->fillRect(option.rect, Qt::transparent);
        } else {
            // 绘制背景色
            painter->fillRect(option.rect, Qt::transparent);

            // 绘制边框
            painter->setPen(Qt::white);


            // 绘制上边框
            painter->drawLine(opt.rect.topLeft(), opt.rect.topRight());

            // 绘制下边框
            painter->drawLine(opt.rect.bottomLeft(), opt.rect.bottomRight());

            // 获取当前选中的项
            QString currentText = index.model()->data(index, Qt::DisplayRole).toString();

            // 绘制文本
            painter->setPen(Qt::black);
            painter->drawText(option.rect, Qt::AlignVCenter | Qt::AlignLeft | Qt::TextSingleLine, currentText);

            // 绘制下拉箭头
            QRect arrowRect = QRect(option.rect.right() - 20, option.rect.top() + 4, 16, 16);
            painter->drawPixmap(arrowRect, QPixmap(":/Resource/Ch.png"));
        }
    } else if (index.data().isValid()) {
        // 绘制背景和文本
        QStyleOptionViewItem opt = option;
        initStyleOption(&opt, index);
        opt.widget->style()->drawControl(QStyle::CE_ItemViewItem, &opt, painter, opt.widget);

        // 绘制边框
        painter->save();
        painter->setPen(Qt::white);


        // 绘制上边框
        painter->drawLine(opt.rect.topLeft(), opt.rect.topRight());

        // 绘制下边框
        painter->drawLine(opt.rect.bottomLeft(), opt.rect.bottomRight());
        painter->restore();
    }   else {
        QStyledItemDelegate::paint(painter, option, index);
    }

    if (index.model()->hasChildren(index)) {
        
        // 检查图标是否加载成功
        if (m_pOpenIcon->isNull()) {
            qDebug() << "Failed to load open_icon.png";
        }
        if (m_pCloseIcon->isNull()) {
            qDebug() << "Failed to load closed_icon.png";
        }
        QStyleOptionButton buttonOpt;
        buttonOpt.rect = option.rect.adjusted(option.rect.width() - 30, 0, 0, 0);
        buttonOpt.state = opt.state;

        // 设置图标
        buttonOpt.icon = opt.state & QStyle::State_Open ? *m_pOpenIcon : *m_pCloseIcon;
        buttonOpt.features = QStyleOptionButton::None;

        // 直接绘制图标
        if (opt.state & QStyle::State_Open) {
            m_pOpenIcon->paint(painter, buttonOpt.rect, Qt::AlignCenter, opt.state & QStyle::State_Enabled ? QIcon::Normal : QIcon::Disabled);
        } else {
            m_pCloseIcon->paint(painter, buttonOpt.rect, Qt::AlignCenter, opt.state & QStyle::State_Enabled ? QIcon::Normal : QIcon::Disabled);
        }
    }
}

QSize KLCustomDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QSize size = QStyledItemDelegate::sizeHint(option, index);
    size.setWidth(1000);
    size.setHeight(30);
    return size;
}


///进入编辑状态
bool KLCustomDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
{
    if (index.column() == 2) {
        switch (event->type()) {
        case QEvent::MouseButtonPress: {
            if (option.rect.contains(static_cast<QMouseEvent*>(event)->pos())) {
                toggleState(index);
                update(index);
                handleButtonClick(index, model);
            }
            break;
        }
        default:
            break;
        }
    } else if(index.column() == 3) {
        switch (event->type()) {
        case QEvent::MouseButtonPress: {
            if (option.rect.contains(static_cast<QMouseEvent*>(event)->pos())) {
                showComboBox(index, model);
            }
            break;
        }
        default:
            break;
        }
    }
    return QStyledItemDelegate::editorEvent(event, model, option, index);
}

QWidget *KLCustomDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    if (index.column() == 3) {
        if (index.data().isValid()) {
            QComboBox* comboBox = new QComboBox(parent);
            comboBox->addItem("Option 1");
            comboBox->addItem("Option 2");
            comboBox->addItem("Option 3");
            // 使用 QPalette 设置背景色

            CustomComboBoxStyle* customStyle = new CustomComboBoxStyle(comboBox->style());
            comboBox->setStyle(customStyle);
            // 设置固定高度
            comboBox->setFixedHeight(30); // 你可以根据需要调整高度
            return comboBox;
        }
        return nullptr;
    }
    return QStyledItemDelegate::createEditor(parent, option, index);
}

void KLCustomDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    if (index.column() == 3) {
        int value = index.model()->data(index, Qt::EditRole).toInt();
        QComboBox *comboBox = static_cast<QComboBox*>(editor);
        comboBox->setCurrentIndex(value);
    } else {
        QStyledItemDelegate::setEditorData(editor, index);
    }
}

void KLCustomDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    if (index.column() == 3) {
        QComboBox *comboBox = static_cast<QComboBox*>(editor);
        int value = comboBox->currentIndex();
        model->setData(index, value, Qt::EditRole);
        model->setData(index, comboBox->currentText(), Qt::DisplayRole);
    } else {
        QStyledItemDelegate::setModelData(editor, model, index);
    }
}

void KLCustomDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
        editor->setGeometry(option.rect);
}

void KLCustomDelegate::saveNewDataTobase(const QString &name, const QString &mcc, const QString &mnc, const bool isNewItem)
{

    emit dataChamged();
}


void KLCustomDelegate::handleButtonClick(const QModelIndex &index, QAbstractItemModel *model)
{
    // 在这里处理按钮点击事件
    QMessageBox::information(nullptr, "Button Clicked", QString("Button clicked at index: %1-%2").arg(index.row()).arg(index.column()));

    // 更新模型数据（例如，改变某一行的数据）
    QStandardItemModel *standardModel = qobject_cast<QStandardItemModel*>(model);
    if (standardModel) {
        QStandardItem *item = standardModel->item(index.row(), 0); // 更新第0列的数据
        if (item) {
            item->setText("Clicked");
            standardModel->dataChanged(index, index);
        }
    }
}

void KLCustomDelegate::showComboBox(const QModelIndex &index, QAbstractItemModel *model)
{
    QTreeView *treeView = qobject_cast<QTreeView*>(parent());
    if (treeView) {
        treeView->edit(index);  // 直接打开编辑器

        // 确保 QComboBox 显示下拉列表
        QComboBox *comboBox = qobject_cast<QComboBox*>(treeView->indexWidget(index));
        if (comboBox) {
            comboBox->showPopup();
        }
    }
}

ButtonState KLCustomDelegate::getState(const QModelIndex &index) const
{
    if (m_buttonStates.contains(index)) {
        return m_buttonStates[index];
    }
    return StateNormal;
}

void KLCustomDelegate::toggleState(const QModelIndex &index)
{
    ButtonState currentState = getState(index);
    ButtonState nextState;

    switch (currentState) {
    case StateNormal:
        nextState = StateSelected;
        break;
    case StateSelected:
        nextState = StateDisabled;
        break;
    case StateDisabled:
        nextState = StateNormal;
        break;
    }

    m_buttonStates[index] = nextState;
}

void KLCustomDelegate::update(const QModelIndex &index) const
{
    if (index.isValid()) {
        QTreeView *treeView = qobject_cast<QTreeView*>(parent());
        if (treeView) {
            treeView->viewport()->update();
        }
    }
}
